#include "FSM.h"
#include "Delay_LCD.h"
#include "lcd.h"
#include "gui.h"
#include "Key_change.h"
#include "Cursor_selection.h"
#include "Close_System.h"


StateMachine sm;

State handle_MENU_1(Event event)
{
    switch (event)
	{
        case EVENT_RIGHT:
        case EVENT_LEFT:
            return MENU_2;
        case EVENT_UP:
        case EVENT_DOWN:
            return MENU_3;
        default:
            return MENU_1;
    }
}

State handle_MENU_2(Event event)
{
    switch (event) {
        case EVENT_RIGHT:
        case EVENT_LEFT:
            return MENU_1;
        case EVENT_DOWN:
        case EVENT_UP:
            return MENU_4;
        default:
            return MENU_2;
    }
}

State handle_MENU_3(Event event)
{
    switch (event) {
        case EVENT_RIGHT:
        case EVENT_LEFT:
            return MENU_4;
        case EVENT_UP:
        case EVENT_DOWN:
            return MENU_1;
		case EVENT_IN:
			return Close_the_system;
        default:
            return MENU_3;
    }
}

State handle_MENU_4(Event event)
{
    switch (event) {
        case EVENT_RIGHT:
        case EVENT_LEFT:
            return MENU_3;
        case EVENT_DOWN:
        case EVENT_UP:
            return MENU_2;
        default:
            return MENU_4;
    }
}

State handle_Close_the_system(Event event)
{
    switch (event) {
        case EVENT_RIGHT:
        case EVENT_LEFT:
        case EVENT_DOWN:
        case EVENT_UP:
		case EVENT_IN:
			LCD_LED(1);//µãÁÁ±³¹â
			SyeTem_Menu_1234();//ÖÐÎÄ×ÖÌåÊ¾Àý²âÊÔ
			Buzzer_Start();
            return MENU_1;
        default:
            return Close_the_system;
    }
}


// 初始化状态机
void initialize_state_machine(StateMachine *sm)
{
    sm->current_state = MENU_1;
    sm->state_handlers[MENU_1] = handle_MENU_1;
    sm->state_handlers[MENU_2] = handle_MENU_2;
    sm->state_handlers[MENU_3] = handle_MENU_3;
    sm->state_handlers[MENU_4] = handle_MENU_4;
	sm->state_handlers[Close_the_system] = handle_Close_the_system;
	
}

// 处理事件
void process_event(StateMachine *sm, Event event)
{
    StateHandler handler = sm->state_handlers[sm->current_state];
    sm->current_state = handler(event);

    PROCESS_the_state(sm->current_state);
}

void PROCESS_the_state(State current_state)
{
    switch(current_state)
    {
        case MENU_1:
        case MENU_2:
        case MENU_3:
        case MENU_4:
            KEY_MENU_CHOOSE();
            break;
        case Close_the_system:
            CLOSE_the_system();
            break;
    }
}


void FSM_Init(void)
{
    initialize_state_machine(&sm);
}
